package org.brakepedal.server.support.bluetooth;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.microedition.io.Connector;
import javax.microedition.io.OutputConnection;
import java.io.Closeable;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

/**
 * Date: 2024/4/1 13:00
 *
 * @author Huanyu Mark
 */
@Lazy
@Slf4j
@Component
@Scope("prototype")
public class BtEncodeBroker implements Closeable {
    private static final Random numberGenerator = new Random();

    private final BtService service;

    private OutputConnection connection;

    private OutputStream out;

    @Setter
    private BtFrameEncoder btFrameEncoder = new DefaultBtFrameEncoder();

    private static final TimeZone currentTimeZone = TimeZone.getTimeZone("Asia/Shanghai");

    public BtEncodeBroker(BtService service) {
        this.service = service;
    }
    public BtEncodeBroker open() throws IOException {
//        connection = ((OutputConnection) Connector.open(String.format("btspp://%s:%s", device.getAddress(), 1)));
        connection = ((OutputConnection) Connector.open(service.getConnectionUrl()));
        out = connection.openOutputStream();
        return this;
    }

    public void encodeAndSend(BtFrame frame) throws IOException {
        btFrameEncoder.encode(out, frame);
    }

    public void testSend() throws IOException {
        Calendar current = Calendar.getInstance(currentTimeZone);
        var frame =  new BrakePedalStateFrame(
                numberGenerator.nextInt(100),
                numberGenerator.nextInt(100),
                2024,
                current.get(Calendar.MONTH),
                current.get(Calendar.DAY_OF_MONTH),
                current.get(Calendar.HOUR_OF_DAY),
                current.get(Calendar.MINUTE),
                current.get(Calendar.SECOND));
//        System.out.println(frame);
        btFrameEncoder.encode(out,frame);
    }

    @Override
    public void close() throws IOException {
        if(out != null) {
            out.close();
        }
        if(connection != null) {
            connection.close();
        }
    }
}
